import { ref, unref } from "vue";
export const Auths = ref([]);//权限列表
export const AuthCont = ref(true); //是否开启权限校验，模式是开启

/**
 * 权限校验方法
 * @param {*} key 
 * @returns 
 */
export const AuthCheck = (key) => {
    if (!AuthCont.value) {
        return true;
    };
    let targetIndex = Auths.value.findIndex((item) => {
        return item == key;
    })
    return targetIndex > -1 ? true : false;
}

export const AuthPlugin = {
    install: (app, options) => {
        //注册全局方法
        app.config.globalProperties.$AuthCheck = (key) => {
            if (!AuthCont.value) {
                return true;
            };
            let targetIndex = Auths.value.findIndex((item) => {
                return item == key;
            })
            return targetIndex > -1 ? true : false;
        };
    }
};



/**
 * 直接设置权限： ["userlist:add","userlist:edit"]
 * @param {*} auth 
 */
export const SetAuths = (auth) => {
    Auths.value = unref(auth);
}

/**
 * 开始auth
 */
export const StartAuth = () => {
    AuthCont.value = true;
};
/**
 * 关闭auth
 */
export const CloseAuth = () => {
    AuthCont.value = false;
};

/**
 * 通过菜单更新权限
 * @param {*} menuList 
 */
export const UpdateAuthByMenu = (menuList) => {
    recursiveUpdate(unref(menuList));
};

function recursiveUpdate(menuList) {
    menuList.forEach((item) => {
        if (item.buttons && item.buttons.length > 0) {
            let buttons = item.buttons;
            buttons.forEach((bItem) => {
                Auths.value.push(item.url + ":" + bItem.url);
            });
        };
        if (item.child && item.child.length > 0) {
            recursiveUpdate(item.child);
        }
    })
};